import os
import subprocess
from tkinter import *
import tkinter.ttk as ttk
import tkinter.filedialog
import threading
import time
import re
from tkinter import messagebox
import chardet
from word import WordReport
FluentPath = ""
ScriptPath = ""
ScriptRootPath = ""
sema: int = 4
cpuCore = os.cpu_count()
def popupmenu(event):
    mainmenu.post(event.x_root, event.y_root)
    print("tight")

def ChFluentPath():
    global FluentPath
    FluentPath = tkinter.filedialog.askdirectory(initialdir='C:/Program Files/ANSYS Inc/')
    print(FluentPath)
    if FluentPath != '':
        lb1.config(text='Fluent路径：'+FluentPath)
    else:
        lb1.config(text='Fluent路径：未选择')

def ChScriptPath():
    global ScriptPath
    global ScriptRootPath
    ScriptPath = tkinter.filedialog.askopenfilename(initialdir='C:/Users/Leo/Desktop/WLB项目',filetypes=[("JOU", "jou")])
    if ScriptPath != '':
        wordlist = re.split('/', ScriptPath)
        ScriptRootPath = ""
        for i in range(0, len(wordlist) - 1):
            if i!=len(wordlist) - 2:
                ScriptRootPath += wordlist[i] + '/'
            else:
                print("!2")
                ScriptRootPath += wordlist[i]
        lb2.config(text='脚本文件：' + ScriptPath)
        lb3.config(text='脚本文件根目录路径：' + ScriptRootPath)
    else:
        lb2.config(text='脚本文件：未选择')

def ChScriptRootPath():
    global ScriptRootPath
    ScriptRootPath = tkinter.filedialog.askdirectory(initialdir='C:/Users/Leo/Desktop/WLB项目')
    if ScriptRootPath != '':
        lb3.config(text='脚本文件根目录路径：' + ScriptRootPath)
    else:
        lb3.config(text='脚本文件根目录路径：未选择')

def CmdStart():
    txt.config(state=NORMAL)
    command = "exec.bat"
    ret = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, stdout=subprocess.PIPE)
    try:
        for i in iter(ret.stdout.readline, 'b'):
            # line_list = i.split('\r\n')
            if i:
                ret = chardet.detect(i)
                txt.insert(END, i.decode(ret['encoding']))
                txt.see(END)
                print(i.decode(ret['encoding']))
            else:
                break
        for i in iter(ret.stderr.readline, 'b'):
            # line_list = i.split('\r\n')
            if i:
                ret = chardet.detect(i)
                txt.insert(END, i.decode(ret['encoding']))
                txt.see(END)
                print(i.decode(ret['encoding']))
            else:
                break
    finally:
        txt.insert(END, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + "开始生成报告\n")
        txt.see(END)
        wd = WordReport()
        path = wd.addItem(ScriptRootPath)
        txt.insert(END, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + "报告生成完毕\n")
        txt.see(END)
        txt.insert(END, "报告保存路径："+path+"\n")
        txt.see(END)
        txt.insert(END, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " 结束\n")
        txt.see(END)
        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " 结束")
        txt.config(state=DISABLED)
        btn2.config(state=NORMAL)

def Start():
    # txt.delete(1.0, END)
    btn2.config(state=DISABLED)
    txt.config(state=NORMAL)
    txt.insert(END, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " 开始分析\n")
    file_handle = open('exec.bat', 'w')
    file_handle.write('@ set PATH=' + FluentPath + '/;%PATH%\n')
    file_handle.write('@ cd ' + ScriptRootPath + '\n')
    if DelCheckVar.get() == 1:
        file_handle.write('@ fluent -wait 3ddp -t'+str(sema)+' -i ' + ScriptPath + '\n')
    else:
        file_handle.write('@ fluent -hidden -wait 3ddp -t'+str(sema)+' -i ' + ScriptPath + '\n')
    file_handle.write('@ del *.trn\n')
    file_handle.close()
    try:
        t1 = threading.Thread(target=CmdStart)
        t1.setDaemon(True)
        t1.start()
    except:
        txt.insert(END, '开始失败\n')
        txt.config(state=DISABLED)
        btn2.config(state=NORMAL)


def pop_up_box():
    global sema
    # global btn4
    winNew = Toplevel(root)
    winNew.geometry('300x100')
    winNew.title('设置核数')
    def com():
        try:
            num = int(e1.get())  # 获取e1的值，转为浮点数，如果不能转捕获异常
            if(num>cpuCore):
                messagebox.showwarning('警告', '超出范围')
            else:
                sema = int(e1.get())
                lb3.config(text='计算核数'+str(sema)+'<计算核数'+str(cpuCore))
                winNew.destroy()
        except:
            messagebox.showwarning('警告', '请输入数字')
    var = tkinter.StringVar()  # 这即是输入框中的内容
    var.set(str(sema))
    e1 = Entry(winNew,textvariable=var)
    e1.pack()
    Button(winNew, text='保存', command=com).pack()
    l1 = Label(winNew, text='只能数字。最大值为'+str(cpuCore))
    l1.pack()

def edit_Semaphore():
    winNew = Toplevel(root)
    winNew.geometry('500x200')
    winNew.title('设置核数')

    var = IntVar()
    scl = Scale(winNew, orient=HORIZONTAL, length=400, from_=1, to=200, tickinterval=20, resolution=1,
                variable=var)
    scl.set(sema)
    scl.bind('<ButtonRelease-1>', lambda event:edit(var.get(),lb))
    scl.pack()
    lb = Label(winNew, text='当前设置数值：%d' % sema)
    lb.pack()
    btClose = Button(winNew, text='关闭', command=winNew.destroy)
    btClose.place(relx=0.7, rely=0.5)
def edit(num,lb):
    global sema
    sema = num
    lb.config(text='当前设置数值：%d' % sema)
if __name__ == '__main__':

    root = Tk()
    root.geometry('800x600')
    root.title('WLB分析')
    tab_main = ttk.Notebook()  # 创建分页栏
    tab_main.place(relx=0, rely=0, relwidth=1, relheight=1)
    FluentFrame = Frame(tab_main)  # 创建第一页框架
    tab_main.add(FluentFrame, text='Fluent')  # 将第一页插入分页栏中
    FluentFrame2 = Frame(tab_main)  # 创建第一页框架
    tab_main.add(FluentFrame2, text='Fluent2')  # 将第一页插入分页栏中

    mainmenu = Menu(root)
    menuFile = Menu(mainmenu)  # 菜单分组 menuFile
    mainmenu.add_cascade(label="文件", menu=menuFile)
    # menuFile.add_command(label="选择Fluent路径...", command=ChFluentPath)
    # menuFile.add_command(label="选择脚本文件...", command=ChScriptPath)
    # menuFile.add_command(label="选择脚本文件根目录...", command=ChScriptRootPath)
    menuFile.add_separator()  # 分割线
    menuFile.add_command(label="退出", command=root.destroy)


    lb1 = Label(FluentFrame, text='Fluent路径：未选择')
    lb1.place(relx=0.2, rely=0.02, relwidth=0.8, relheight=0.1)
    lb2 = Label(FluentFrame, text='脚本文件路径：未选择')
    lb2.place(relx=0.2, rely=0.1, relwidth=0.8, relheight=0.1)
    print()
    lb3 = Label(FluentFrame, text='计算核数'+str(sema)+'<计算核数'+str(cpuCore))
    lb3.place(relx=0.2, rely=0.18, relwidth=0.8, relheight=0.1)

    DelCheckVar = IntVar()
    ch = Checkbutton(FluentFrame, text='分析时显示界面', variable=DelCheckVar, onvalue=1, offvalue=0)
    ch.place(relx=0.1, rely= 0.35)

    btn1 = Button(FluentFrame, text='选择Fluent路径', command=ChFluentPath)
    btn1.place(relx=0.1, rely=0.04, relwidth=0.2, relheight=0.05)
    btn2 = Button(FluentFrame, text='选择脚本文件', command=ChScriptPath)
    btn2.place(relx=0.1, rely=0.12, relwidth=0.2, relheight=0.05)
    btn4 = Button(FluentFrame, text='设置核数', command=pop_up_box)
    btn4.place(relx=0.1, rely=0.20, relwidth=0.2, relheight=0.05)
    btn2 = Button(FluentFrame, text='开始分析', command=Start)
    btn2.place(relx=0.1, rely=0.4, relwidth=0.8, relheight=0.05)

    txt = Text(FluentFrame)
    txt.config(state=DISABLED)
    txt.place(rely=0.5, relheight=0.5, relwidth=1.0)
    txt.tag_config("tag_1", foreground="red")
    #2
    # lb1 = Label(FluentFrame2, text='Fluent路径：未选择')
    # lb1.place(relx=0.2, rely=0.02, relwidth=0.8, relheight=0.1)
    # lb2 = Label(FluentFrame2, text='脚本文件路径：未选择')
    # lb2.place(relx=0.2, rely=0.1, relwidth=0.8, relheight=0.1)
    # lb3 = Label(FluentFrame2, text='脚本文件根目录路径：未选择')
    # lb3.place(relx=0.2, rely=0.18, relwidth=0.8, relheight=0.1)
    #
    # DelCheckVar = IntVar()
    # ch = Checkbutton(FluentFrame2, text='分析时显示界面', variable=DelCheckVar, onvalue=1, offvalue=0)
    # ch.place(relx=0.1, rely=0.35)
    #
    # btn1 = Button(FluentFrame2, text='选择Fluent路径', command=ChFluentPath)
    # btn1.place(relx=0.1, rely=0.04, relwidth=0.2, relheight=0.05)
    # btn2 = Button(FluentFrame2, text='选择脚本文件', command=ChScriptPath)
    # btn2.place(relx=0.1, rely=0.12, relwidth=0.2, relheight=0.05)
    # btn3 = Button(FluentFrame2, text='选择脚本文件根目录', command=ChScriptRootPath)
    # btn3.place(relx=0.1, rely=0.20, relwidth=0.2, relheight=0.05)
    # btn4 = Button(FluentFrame2, text='设置核数', command=edit_Semaphore)
    # btn4.place(relx=0.1, rely=0.28, relwidth=0.2, relheight=0.05)
    # btn2 = Button(FluentFrame2, text='开始分析', command=Start)
    # btn2.place(relx=0.1, rely=0.4, relwidth=0.8, relheight=0.05)
    #
    # txt = Text(FluentFrame2)
    # txt.config(state=DISABLED)
    # txt.place(rely=0.5, relheight=0.5, relwidth=1.0)
    # txt.tag_config("tag_1", foreground="red")

    root.config(menu=mainmenu)
    root.bind('Button-3', popupmenu)  # 根窗体绑定鼠标右击响应事件
    root.mainloop()
